import { Input, InputNumber, Message, Radio, Select } from '@arco-design/web-react';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { ValidateRule } from '../../../types';
import DetailItem from '../../../components/detailItem';
import DetailModal from '../../../components/detailModal';
import LoadingMask from '../../../components/loadingMask';
import { validateField,getDict,dictDataOptions} from '../../../utils/utils';
import { apiGetPayCouponList } from '../../../api';
import { PayCoupon } from '../../../types';
import { apiGetPayCouponCardUserList } from '../../../api';
import { PayCouponCardUser } from '../../../types';
import { apiPayCouponCardUser } from '../../../api';

interface Props {
  id: number | string | undefined;
  onCancel: (update?: boolean) => void;
}

type Option = { label: string; value: number; couponType: string };
const rule: ValidateRule = {
  coupon: { required: true, message: '请选择优惠券' },
  count: { required: true, message: '请填写赠送数量' },
};
const PAY_COUPON_COUPON_TYPE = 'pay_coupon_coupon_type';
// 赠送流量券弹框
export default function GiveCouponDialog({ id, onCancel }: Props) {
  const [dictDatas, setDictDatas] = useState<Record<string, any>>({});
  useEffect(() => {
    async function fetchDictData() {
      const data = await getDict(PAY_COUPON_COUPON_TYPE);
      setDictDatas(data);
    }

    fetchDictData();
  }, []); 

  const [hasCouponList, setHasCouponList] = useState<PayCouponCardUser[]>([]);
  const [couponType, setCouponType] = useState('flow');
  const [couponList, setCouponList] = useState<Option[]>([]);
  const [coupon, setCoupon] = useState<number>();
  const [count, setCount] = useState(1);
  const [remark, setRemark] = useState('');
  // 数据验证结果
  const [errorData, setErrorData] = useState<{ [x: string]: string }>({});
  useEffect(() => {
    getPayCouponList();
    // getHasCouponList();
  }, []); // eslint-disable-line
  // 获取已送过的优惠券列表
  // async function getHasCouponList() {
  //   try {
  //     let res = await apiGetPayCouponCardUserList(1, 1000, { sourceType: 'send', cardId: id });
  //     let data = res.data;
  //     if (data.code === 200) {
  //       setHasCouponList(data.rows ?? []);
  //     } else {
  //       setHasCouponList([]);
  //     }
  //   } catch (e: any) {}
  // }

  // 获取流量券列表
  async function getPayCouponList() {
    try {
      let res = await apiGetPayCouponList(1, 1000, { status: '0' });
      let data = res.data;
      if (data.code === 200) {
        let _list = data.rows.map((i: PayCoupon) => ({
          label: i.locuponName,
          value: i.id,
          couponType: i.couponType,
        }));
        setCouponList(_list);
      } else {
        setCouponList([]);
        Message.warning(data.msg ?? '获取流量券列表失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '获取流量券列表失败');
    }
  }

  async function handleConfirm() {
    let validateRes = validateField({ coupon, count }, rule);
    setErrorData(validateRes);
    if (Object.keys(validateRes).length) return;
    if (!!hasSend && !remark?.trim()) {
      return Message.warning('请在备注中填写重复赠送的原因');
    }
    const resData:any = couponList?.find(item=>item.value === coupon) || {};
    let submitData = {
      cardId: id,
      couponNum: count,
      remark: remark,
      lcouponStatus: 0,
      locuponId: resData.id,
      locuponName: resData.locuponName,
      couponInfo: resData.couponInfo,
      createBy: resData.createBy,
      createTime: resData.createTime,
      deductionAmount: resData.deductionAmount,
      delFlag: resData.delFlag,
      lcouponType: resData.lcouponType,
      updateBy: resData.updateBy,
      updateTime: resData.updateTime,
      reductionAmount: resData.reductionAmount,
      status: resData.status,
      obsoleteTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    }
    LoadingMask.show('正在赠送...');
    try {
      let res = await apiPayCouponCardUser(submitData);
      let data = res.data;
      if (data.code === 200) {
        Message.success(data.msg ?? '赠送成功');
        onCancel(true);
      } else {
        Message.warning(data.msg ?? '赠送失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '赠送失败');
    } finally {
      LoadingMask.hide();
    }
  }
  // let list = (couponList ?? []).filter((i) => i.couponType === couponType);
  let hasSend = hasCouponList.find((i) => i.couponId === coupon);
  return (
    <DetailModal title="赠送卡券" show className="bw-80" onCancel={() => onCancel()} onConfirm={handleConfirm}>
      {/* <DetailItem label="历史赠送" labelSpan={5} outlet={4}>
        {(hasCouponList ?? []).length > 0
          ? hasCouponList!.map((i, idx) => (
              <div className="pt-5" key={i.id}>
                {i.couponName}
                <div>
                  赠送时间:{dayjs(i.createTime!).format('YYYY-MM-DD')}
                  <span className="mr-10" />
                  有效期至：{dayjs(i.validEndTime!).format('YYYY-MM-DD')}
                </div>
                {idx < hasCouponList!.length - 1 && <div className="border-top" />}
              </div>
            ))
          : '无'}
      </DetailItem> */}
      {/* <DetailItem label="选择类型" labelSpan={5} outlet={4}>
        <Radio.Group
          options={dictDataOptions(dictDatas[PAY_COUPON_COUPON_TYPE])}
          value={couponType}
          onChange={(v) => setCouponType(v)}
        />
      </DetailItem> */}
      <DetailItem
        label="优惠券"
        required
        labelSpan={5}
        outlet={4}
        tips={hasSend ? '已赠送过此优惠券,请填写备注' : ''}
        error={errorData?.coupon}
      >
        <Select
          showSearch
          filterOption={(inputValue, option) =>
            option.props.value.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0 ||
            option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
          }
          allowClear
          className="m-select"
          options={couponList}
          value={!coupon ? undefined : coupon}
          onChange={(v) => setCoupon(v)}
        />
      </DetailItem>
      <DetailItem label="赠送数量" required labelSpan={5} outlet={4} error={errorData?.count}>
        <InputNumber className="m-input" min={1} value={count} onChange={(v) => setCount(v)} />
      </DetailItem>
      <DetailItem label="备注" required={!!hasSend} labelSpan={5} outlet={4}>
        <Input.TextArea className="m-input" autoSize={{ minRows: 3 }} value={remark} onChange={(v) => setRemark(v)} />
      </DetailItem>
    </DetailModal>
  );
}
